package com.lantosec.hmrp.core.ureport;

import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.provider.image.ImageProvider;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

@Component
public class UploadImageProvider implements ImageProvider {

    public UploadImageProvider() {
    }

    @Autowired
    private ISysUploadsService uploadsService;

    @Override
    public InputStream getImage(String path) {
        try {
            InputStream inputStream = null;
            // base64 直接转成流
            if (path.contains("base64")) {
                path = path.substring(path.indexOf("base64,") + "base64,".length());
                inputStream = new ByteArrayInputStream(Base64.decodeBase64(path));
            }
            else{
                String imgUrl = "";
                // 图片的url
                if (path.startsWith("http")) {
                    imgUrl = path;
                }
                // 上传图片的Id
                else if(path.length() == 32) {
                    imgUrl = uploadsService.queryPictureUrlById(path);
                    System.out.println(imgUrl);
                }
                if(StringUtils.isNotEmpty(imgUrl)) {
                    URL url = new URL(imgUrl);
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    inputStream = connection.getInputStream();
                }
            }
            return inputStream;
        } catch (IOException e) {
            throw new ReportComputeException(e);
        }
    }


    @Override
    public boolean support(String path) {
        System.out.println(path);
       /* if (path.startsWith(":upload:") || path.startsWith("upload:")) {
            return true;
        }
        return false;*/
       return true;
    }
}
